package homework1;

import java.util.ArrayList;
import java.util.concurrent.*;

/**
 * @Author han
 * 使用CompletableFuture
 */
public class ByCountDownLatch {

    public static void main(String[] args) throws InterruptedException, ExecutionException {
        // 开始时间
        long start=System.currentTimeMillis();

        ExecutorService executor = Executors.newFixedThreadPool(2);
        ArrayList<FutureTask<Integer>> list = new ArrayList<>();
        CountDownLatch latch = new CountDownLatch(2);

        for (int i = 0; i < 2; i++) {
            // 两个线程做同样的事情，这里用作模拟
            FutureTask<Integer> task = new FutureTask<Integer>(new MyCallable(latch));
            list.add(task);
            executor.submit(task);
        }
        // 等待子线程全部完成
        latch.await();
        executor.shutdown();
        for (FutureTask<Integer> task: list) {
            System.out.println("计算结果为："+ task.get());
        }

        while (!executor.isTerminated());

        System.out.println("退出主线程");

    }

    private static int sum() {
        return fibo(36);
    }

    private static int fibo(int a) {
        if ( a < 2)
            return 1;
        return fibo(a-1) + fibo(a-2);
    }

    static class MyCallable implements Callable<Integer> {

        private CountDownLatch latch;

        public MyCallable(CountDownLatch latch) {
            this.latch = latch;
        }

        @Override
        public Integer call() throws Exception {
            int sum = ByCountDownLatch.sum();
            System.out.println(Thread.currentThread().getName() + "正在计算中");
            latch.countDown();
            return sum;
        }
    }
}
